package com.itchen.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.itchen.common.exception.CustomException;
import com.itchen.domain.entity.User;
import com.itchen.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtTokenUtils {

    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);
    private static  UserService userService;

    public JwtTokenUtils(UserService userService) {
        JwtTokenUtils.userService = userService;
    }

    /**
     * jwt密钥
     */
    private static final Algorithm sign = Algorithm.HMAC256("template");

    /**
     * 生成token
     */
    public static String genToken(User user) {
        return JWT.create().withAudience(String.valueOf(user.getId())) // 将 userid 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(user.getPassword())); // 使用用户密码作为密钥
    }

    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser() {
        String token = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String requestURI = request.getRequestURI();

            token = request.getHeader("token");
            if (StrUtil.isBlank(token)) {
                token = request.getParameter("token");
            }

            if (requestURI.equals("/auth/login")) {
                return null;
            }

            if (StrUtil.isBlank(token)) {
                log.error("获取当前登录的token失败， token: {}", token);
                throw new CustomException("获取当前登录的token失败");
            }
            // 解析token，获取用户的id
            String userId = JWT.decode(token).getAudience().get(0);
            User user = userService.getById(userId);
            
            if (user == null) {
                log.error("token对应的用户不存在， userId: {}", userId);
                throw new CustomException("token对应的用户不存在");
            }
            
            try {
                // 验证token，与JwtInterceptor中使用相同的验证逻辑
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                jwtVerifier.verify(token);
            } catch (Exception e) {
                log.error("token验证失败", e);
                throw new CustomException("token验证失败");
            }
            
            return user;
        } catch (Exception e) {
            log.error("获取当前登录的用户信息失败, token={}", token, e);
            throw new CustomException("获取当前登录的用户信息失败");
        }
    }
}